package com.hfb.mashibing.alip8.designpattern._08ChainOfResponsibility;

import java.util.LinkedList;
import java.util.List;

/**
 * 责任链：
 *  处理 request(1->2->3) V1
 *  处理 response(1->2->3) V2
 *  处理  V3
 *       request(1->2->3)
 *       response(3->2->1)
 *  处理 V4 完全模拟 Serverlet 中的 FilterChain
 *      request(1->2->3)
 *      response(3->2->1)
 */

public class Servlet_MainV4 {
    public static void main(String[] args) {
        Request request = new Request();
        request.str = "大家好：）<script>欢迎👏🏻访问 http://mashibing.com 大家都是 996 ";

        Response response = new Response();

        FilterChain chain = new FilterChain();
        chain.add(new HTMLFilter())
             .add(new SensitiveFilter());
        chain.doFilter(request, response);

        System.err.printf("request:%s\n", request.str);
        System.err.printf("response:%s\n", response.str);
    }


    interface Filter {
        boolean doFilter(Request request, Response response, FilterChain filterChain);
    }
    static class FilterChain {
        List<Filter> filters = new LinkedList<>();
        int index = 0;

        FilterChain add(Filter filter){
            filters.add(filter);
            return this;
        }

        public boolean doFilter(Request request, Response response) {
            if (index == filters.size()) {
                return false;
            }
            Filter f = filters.get(index);
            index ++;

            return f.doFilter(request, response, this);
        }
    }
    static class HTMLFilter implements Filter{
        @Override
        public boolean doFilter(Request request, Response response, FilterChain filterChain) {
            request.str = request.str.replaceAll("<", "[")
                                     .replaceAll(">", "]")
                                     + "HTMLFilter()";
            filterChain.doFilter(request,response);
            response.str += "--HTMLFilter()\t";
            return true;
        }
    }
    static class SensitiveFilter implements Filter{
        @Override
        public boolean doFilter(Request request, Response response,FilterChain filterChain) {
            request.str = request.str.replaceAll("996","995")
                                     + "SensitiveFilter()";
            filterChain.doFilter(request,response);
            response.str += "--SensitiveFilter()\t";
            return true;
        }
    }
    static class Request {
        String str = "";
    }
    static class Response {
        String str = "";
    }
}
